package org.ccahouse.ccatrain.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.ccahouse.ccacommons.common.GlobalException;
import org.ccahouse.ccatrain.entity.Audience;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;

public class JwtTokenUtil {
    public static final String AUTH_HEADER_KEY = "Authorization";
    public static final String TOKEN_PREFIX = "Bearer ";
    private static JwtTokenUtil instance;
    private Integer userId;

    public JwtTokenUtil() {
    }

    public Integer getUserId() {
        return userId;
    }

    public void setUserId(Integer userId) {
        this.userId = userId;
    }

    public static JwtTokenUtil getInstance() {
        if (instance == null) {
            instance = new JwtTokenUtil();
        }
        return instance;
    }

    public static Claims parseJwt(String jsonWebToken, String base64Security) {
        try {
            Claims claims = Jwts.parser()
                    .setSigningKey(base64Security)
                    .parseClaimsJws(jsonWebToken).getBody();
            return claims;
        }catch (Exception exception){
            throw new GlobalException("token 验证失败");
        }
    }

    public static String createJwt(Integer userId, String username, Audience audience) {
        Date now = new Date(System.currentTimeMillis());
        JwtBuilder builder = Jwts.builder()
                .claim("userId", userId)
                .setSubject(username)
                .setIssuer(audience.getClientId())
                .setIssuedAt(new Date())
                .setAudience(audience.getName())
                .signWith(SignatureAlgorithm.HS256, audience.getBase64Secret());
        int TTLMillis = audience.getExpiresSecond();
        if (TTLMillis >= 0) {
            Date exp = new Date(System.currentTimeMillis() + TTLMillis);
            builder.setExpiration(exp)  // 过期时间
                    .setNotBefore(now); // 开始时间
        }
        return builder.compact();
    }

    public static Integer getUserId(String token, String base64Security){
        Integer userId = parseJwt(token, base64Security).get("userId", Integer.class);
        return userId;
    }

    public static String md5(String s) {
        try {
            MessageDigest md = MessageDigest.getInstance("SHA");
            md.update(s.getBytes());
            return new BigInteger(md.digest()).toString(32);
        }catch (Exception e) {
            throw new GlobalException("加密失败");
        }
    }
}
